//
//  FriendlistTableViewController.m
//  Weiweiyunshi
//
//  Created by 张旭峰 on 2017/1/22.
//  Copyright © 2017年 王译. All rights reserved.
//

#import "FriendlistTableViewController.h"
#import "OrginformationController.h"
#import "NSString+PinYin.h"
#import "PersonImageTableViewCell.h"
#import "MJRefresh.h"
#import "CNRefreshHeaderView.h"
#import "LoginModel.h"
#import "AddContactViewController.h"
@interface FriendlistTableViewController ()
{
    NSMutableArray *_nameSource;
    NSMutableArray *_nameIndex;
}
@property(nonatomic,strong)NSArray * modelList;
@property(nonatomic,copy)NSString * img;

@property(nonatomic,strong)NSArray<FriendListModel*> * collectionArray;

@end

@implementation FriendlistTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _nameSource = [NSMutableArray array];
    _nameIndex = [NSMutableArray array];
    [self setupUI];
   
    [self loadData];
     [self setupRefresh];
    self.tableView.rowHeight=UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight=200;

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
     [self.tableView registerNib:[UINib nibWithNibName:@"PersonImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
    
    }
-(void)setupUI
{
    UITableView *tableView= [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    tableView.dataSource = self;
//    [self.view addSubview: tableView];
    self.tableView.delegate=self;
    self.tableView.dataSource = self;
    
    self.tableView = tableView;
    
    
    UINib* nib = [UINib nibWithNibName:@"PersontableViewHeadView1" bundle:nil];
    // 获取xib中的视图
    UIView* pictureView = [nib instantiateWithOwner:nil options:nil][0];
    
    // 获取view的宽度
    CGFloat xibW = pictureView.bounds.size.width;
    
    // 获取view的高度
    CGFloat xibH = pictureView.bounds.size.height;
    
    //    // 获取tableView宽度
    CGFloat viewW = self.tableView.bounds.size.width;
    //
    //    // 计算 Header 应该显示的高度
    CGFloat viewH = xibH * viewW / xibW;
    //
    pictureView.frame = CGRectMake(0, 0, viewW, viewH);
    //
    // 创建一个大的headerView
    UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewW, CGRectGetMaxY(pictureView.frame))];
    //
    //    // 把两个子空间都装在大的头部视图当中
    ////    [headerView addSubview:typeView];
    [headerView addSubview:pictureView];
    
    // 把视图放置到tableView的header上
    self.tableView.tableHeaderView =headerView;
    UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ViewClick)];
    
    [headerView addGestureRecognizer:labelTapGestureRecognizer];
    
}

-(void)ViewClick
{
  NSLog(@"ViewClick----->");
    AddContactViewController * VC = [[AddContactViewController alloc]init];
    [self.navigationController pushViewController:VC animated:NO];
    
    
}
-(void)setupRefresh
{
  self.tableView.mj_header=[CNRefreshHeaderView headerWithRefreshingBlock:^{
        [self loadData];
    }];
    
}
-(void)loadData
{
    //    NSArray *arrayyy =[[SQLiteManager sharedSQLiteManager] queryContact1];
    //    if(arrayyy.count == 0)
    //    {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *userId =  [userDefaults objectForKey:@"loginName"];
    NSString *url = [NSString stringWithFormat:@"http://210.72.239.121:8088/SSIL/contact.do?userId=%@&pageNum=1&count=200",userId];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //        NSLog(@"------->>>%@",responseObject);
//        NSArray *array = [NSArray yy_modelArrayWithClass:[FriendListModel class] json:responseObject[@"contact"]];
//        
//        self.collectionArray = array;
        //        [[SQLiteManager sharedSQLiteManager] insertContact1:_modelList];
        
//        NSArray *arrayyy =[[SQLiteManager sharedSQLiteManager] queryContact1];
//        if(arrayyy.count != 0)
//        {
//            
////                        self.collectionArray = [[SQLiteManager sharedSQLiteManager] queryContact1:@"李"];
//            
//        }else{
//            
////            [[SQLiteManager sharedSQLiteManager] insertContact1:_modelList];
//            
//        }
        //        self.collectionArray = [[SQLiteManager sharedSQLiteManager] queryContact1];
        
        
        
        //        self.collectionArray = [[SQLiteManager sharedSQLiteManager]queryContact1:@"李"];
        
        
        
        NSDictionary *dic = responseObject;
        NSArray *array = [NSArray yy_modelArrayWithClass:[FriendListModel class] json:responseObject[@"contact"]];
        NSArray *arr = dic[@"contact"];
        self.collectionArray = array;
        
        _nameSource =[[NSMutableArray alloc]init];
        
        for (int i=0; i<arr.count; i++) {
            NSDictionary *dic1 = arr[i];
            FriendListModel *model = [FriendListModel yy_modelWithDictionary:dic1];
            [_nameSource addObject:model.name];
            //            [dataSource addObject:model];
        }
        _nameIndex = [[_nameSource arrayWithPinYinFirstLetterFormat]mutableCopy];
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        
    }];
    
    
    //    }
    //    else {
    //
    ////        self.collectionArray = [[SQLiteManager sharedSQLiteManager] queryContact1];
    ////        
    //        self.collectionArray = [[SQLiteManager sharedSQLiteManager]queryContact1:@"刘"];
    //        
    //    }
    
    
    //    [self.tableView reloadData];
    
    
   
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    OrginformationController *orinforVC = [[OrginformationController alloc]init];
    NSDictionary *dict = _nameIndex[indexPath.section];
    NSMutableArray *array = dict[@"content"];
    for (FriendListModel * model12 in _collectionArray) {
        if(model12.name ==array[indexPath.row])
        {
            orinforVC.userName =model12.name;
            orinforVC.deptName =model12.company;
            
            orinforVC.pdeptName =model12.dept;
            orinforVC.email =model12.email;
            orinforVC.mobile =model12.mobile;
            orinforVC.img =model12.photo;
            
            orinforVC.vidyoKey = model12.vidyoKey;
            orinforVC.vidyoURL = model12.vidyourl;
            orinforVC.domainName = model12.domainName;
            
            break;
        }
        
    }

//    orinforVC.userName =_collectionArray[indexPath.row].name;
//    orinforVC.deptName =_collectionArray[indexPath.row].company;
//    
//    orinforVC.pdeptName =_collectionArray[indexPath.row].dept;
//    orinforVC.email =_collectionArray[indexPath.row].email;
//    orinforVC.mobile =_collectionArray[indexPath.row].mobile;
//    orinforVC.img =_collectionArray[indexPath.row].photo;
    [self.navigationController pushViewController: orinforVC animated:NO];
    
    
}





- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    NSDictionary *dict = _nameIndex[section];
    NSMutableArray *array = dict[@"content"];
    return [array count];
//     return self.collectionArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PersonImageTableViewCell *cellee1 = [tableView dequeueReusableCellWithIdentifier:@"cell1"forIndexPath:indexPath];
    
    NSDictionary *dict = _nameIndex[indexPath.section];
    NSMutableArray *array = dict[@"content"];
    
    
//    cellee1.textLabel.text = array[indexPath.row];
//    cellee1.imageView sd_setImageWithURL:[NSURL URLWithString:[dict objectForKey:]]
    
//    NSDictionary *dict1 = _nameIndex[indexPath.section];
//    NSMutableArray *array1 = dict[@"content"];
    for (FriendListModel * model12 in _collectionArray) {
        if(model12.name ==array[indexPath.row])
        {
            
             self.img =model12.photo;
            
            
            break;
        }
        
    }

    cellee1.PersonName.text = array[indexPath.row];
    [cellee1.PersonimageView sd_setImageWithURL:[NSURL URLWithString:self.img]];
//    [cellee1.imageView sd_setImageWithURL:[NSURL URLWithString:self.img]];
    
    return cellee1;

    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _nameIndex.count;
}

- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
    //    return self.collectionArray[section];
    
    //    return [self.cityListData allKeys][section];
    NSDictionary *dict = _nameIndex[section];
    NSString *title = dict[@"firstLetter"];
    return title;
}


- (NSArray<NSString*>*)sectionIndexTitlesForTableView:(UITableView*)tableView
{
    
    
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSDictionary *dict in _nameIndex) {
        NSString *title = dict[@"firstLetter"];
        [resultArray addObject:title];
    }
    return resultArray;
    
    //        return self.collectionArray;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    
    return index;
}



- (void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath
{
    
    NSLog(@"--->indexPath---->%@",indexPath);
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        // 滑动删除的时候,一定一定要先删除模型
        
        // 删除模型
        //        [self.contactData removeObjectAtIndex:indexPath.row];
        
        // Delete the row from the data source
        //        [_nameIndex[indexPath.section] removeObjectAtIndex:indexPath.row];
        NSMutableDictionary *dict = _nameIndex[indexPath.section];
        NSMutableArray *title = dict[@"content"];
        if(title.count == 1)
        {
            //            [title removeObjectAtIndex:indexPath.row];
            [_nameIndex removeObjectAtIndex:indexPath.section];
            
            
            //            [dict removeObjectForKey:@"firstLetter"];
            //            [title removeObjectAtIndex:indexPath.row];
            
            //            _nameIndex.count = _nameIndex.count -1;
            
            
        }else{
            [title removeObjectAtIndex:indexPath.row];
        }
        [tableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationFade];
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    
}
- (NSArray<UITableViewRowAction*>*)tableView:(UITableView*)tableView editActionsForRowAtIndexPath:(NSIndexPath*)indexPath
{
    UITableViewRowAction* action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction* _Nonnull action, NSIndexPath* _Nonnull indexPath) {
        
        // 删除模型
        //        [_nameIndex[indexPath.section] removeObjectAtIndex:indexPath.row];
        
        NSMutableDictionary *dict = _nameIndex[indexPath.section];
        NSMutableArray *title = dict[@"content"];
        NSString * friendid = [[NSString alloc]init];
        //        NSDictionary *dict2 = _nameIndex[indexPath.section];
        //        NSMutableArray *array = dict2[@"content"];
        for (FriendListModel * model12 in _collectionArray) {
            if(model12.name ==title[indexPath.row])
            {
                friendid = model12.idd;
                break;
            }
            
        }
        if(title.count ==1){
            //        [title removeObjectAtIndex:indexPath.row];
            //            [_nameIndex removeObjectAtIndex:indexPath.section];
            //            [dict removeObjectForKey:@"firstLetter"];
            //            [dict removeObjectForKey:@"firstLetter"];
            [title removeObjectAtIndex:indexPath.row];
            
        }else{
            [title removeObjectAtIndex:indexPath.row];
        }
        
        

        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationFade];
        
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *userId =  [userDefaults objectForKey:@"loginName"];
        NSString *addUrl = [NSString stringWithFormat:@"http://210.72.239.121:8088/SSIL/MyFriend.do?style=delete&userId=%@&friendId=%@",userId,friendid];
        [WYHttpRequest getWithURLString:addUrl parameters:nil success:^(id responseObject) {
            if ([responseObject[@"Code"]isEqualToString:@"1"]) {
                [MBProgressHUD showSuccessMessage:@"删除成功"];
                        [self loadData];
            }else{
                [MBProgressHUD showErrorMessage:@"删除失败"];
            }
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        }];


        
        // 归档联系人信息
        //        [NSKeyedArchiver archiveRootObject:self.contactData toFile:kFilePath];
    }];
    
    return @[ action1 ];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [self setupRefresh];
}
//- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
//{
//    
//    return 10;
//}


@end
